package com.bf.xpdd.web.controller.analysis;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bf.xpdd.domain.ActivityBean;
import com.bf.xpdd.domain.ActivityItemBean;
import com.bf.xpdd.domain.AnalysisData;
import com.bf.xpdd.domain.AnalysisDealByDay;
import com.bf.xpdd.domain.AnalysisDealByItem;
import com.bf.xpdd.domain.JSONResponse;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.service.ActivityItemService;
import com.bf.xpdd.service.ActivityRecordService;
import com.bf.xpdd.service.ActivityService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.DateUtility;
import com.bf.xpdd.util.JSONTranslator;

/**
 * Analysis controller
 * 
 * @author Fantastic
 * @version 1.0.0 2011-05-31
 * @since 1.0.0
 */
@Controller
@RequestMapping(value = "/analysis")
public class AnalysisController
{

	/**
	 * 活动服务
	 */
	@Autowired
	private ActivityService activityService;

	/**
	 * 活动成交服务
	 */
	@Autowired
	private ActivityRecordService activityRecordService;

	/**
	 * 活动商品服务
	 */
	@Autowired
	private ActivityItemService activityItemService;

	/**
	 * 淘宝平台服务
	 */
	@Autowired
	private TaobaoService taobaoService;

	/**
	 * default page
	 * 
	 * @return page
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String showDefault(HttpServletRequest request)
	{
		// 获取商家信息
		SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");

		try
		{
			// 1查询本月的活动根据当前月份查询当月的活动,月末>=开始时间>=当月1日
			@SuppressWarnings("deprecation")
			List<ActivityBean> activityList = this.activityService.queryActivitiesByMonth(seller,
					new Date().getMonth() + 1);

			// 活动数量
			int actCount = 0;
			// 参与活动人数
			int inCount = 0;

			// 无活动处理
			if (activityList == null || activityList.isEmpty())
			{
				// 有效活动集合
				activityList = new ArrayList<ActivityBean>(0);
			}
			else
			{
				for (ActivityBean tempAct : activityList)
				{
					actCount++;
					inCount += tempAct.getUserSize();
				}
			}

			// 设置活动总数
			request.setAttribute("actCount", actCount);
			// 设置参与总人数
			request.setAttribute("inCount", inCount);
			// 设置活动列表
			request.setAttribute("actList", activityList);

			return "analysis/ana_gloabl";
		}
		catch (BaseException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("error", "获取活动信息异常");
			return "error";
		}

	}

	/**
	 * Request Global Data
	 * 
	 * @return data
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET, value = "/globalData")
	public String requestGlobalData(HttpServletRequest request)
	{
		JSONResponse jsonResponse = new JSONResponse();
		try
		{
			// 获取商家信息
			SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");

			// 当前可用活动
			@SuppressWarnings("deprecation")
			List<ActivityBean> activityList = this.activityService.queryActivitiesByMonth(seller,
					new Date().getMonth() + 1);

			// 无活动处理
			if (activityList == null || activityList.isEmpty())
			{
				jsonResponse.setCode("-1");
				jsonResponse.setMessage("没有任何数据");
				return jsonResponse.toString();
			}

			// 成交次数信息
			List<AnalysisDealByDay> coutList = this.activityRecordService.findDealCountByDay(seller,
					new Date().getMonth() + 1);

			// 分析数据集合
			List<AnalysisData> analysisList = new ArrayList<AnalysisData>(activityList.size());

			// 当月天数
			int daysOfMonth = DateUtility.getMaxDayOfMonth();

			// 组装数据
			AnalysisData el;
			for (ActivityBean tempAct : activityList)
			{
				el = new AnalysisData();
				el.setName(tempAct.getAname());
				el.setData(new int[daysOfMonth]);

				for (AnalysisDealByDay tempDeal : coutList)
				{
					if (tempDeal.getActivityId() == tempAct.getAid())
					{
						el.getData()[tempDeal.getDay() - 1] = tempDeal.getCount();
					}
				}

				analysisList.add(el);
			}

			String data = JSONTranslator.toJSON(analysisList, "utf-8", "utf-8");
			jsonResponse.setCode("0");
			jsonResponse.setJson(data);

			return jsonResponse.toString();
		}
		catch (BaseException e)
		{
			jsonResponse.setCode("-2");
			jsonResponse.setMessage("获取数据失败");
			return jsonResponse.toString();
		}
	}

	/**
	 * Request Global Data
	 * 
	 * @return data
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/activity_{id}")
	public String showActivity(@PathVariable String id, HttpServletRequest request)
	{
		try
		{
			// 获取商家信息
			SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
			
			long actId = Long.parseLong(id);
			
			//获取指定活动信息
			ActivityBean activity = this.activityService.queryActivityBeanById(actId);
			
			//校验该活动是否数据当前用户
			if(!seller.getNick().equals(activity.getNick()))
			{
				request.setAttribute("error", "非法的请求");
				return "error";
			}
			
			//获取该活动下 本月 成交数量最多的6个商品
			//数据格式为，item_name, deal_count
			List<AnalysisDealByItem> dataList = this.activityRecordService.findDealCountByActivity(actId, new Date().getMonth() + 1);
			
			//size
			int size = dataList.size();
			
			//生成相应格式数据
			//数据名称
			String title = activity.getAname();
			
			//x分段名称
			String[] xNameArr = new String[size];
			
			//x分段数据
			int[] inCountArr = new int[size];
			
			for(int i = 0; i < size; i++)
			{
				xNameArr[i] = dataList.get(i).getItemName();
				inCountArr[i] = dataList.get(i).getInCount();
			}
			
			request.setAttribute("title", title);
			request.setAttribute("xNameArr", JSONTranslator.toJSON(xNameArr, "utf-8", "utf-8"));
			request.setAttribute("inCountArr", JSONTranslator.toJSON(inCountArr, "utf-8", "utf-8"));
			return "analysis/ana_activity";
		}
		catch (BaseException e)
		{
			request.setAttribute("error", "请求数据异常");
			return "error";
		}
	}
	
	/**
	 * Request Global Data
	 * 
	 * @return data
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/item_{id}")
	public String showItem(@PathVariable String id, HttpServletRequest request)
	{
		try
		{
			// 获取商家信息
			SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
			
			long itemId = Long.parseLong(id);
			
			//获取指定活动信息
			ActivityItemBean item = this.activityItemService.queryActivityItemById(itemId);
			
			//获取指定活动信息
			ActivityBean activity = this.activityService.queryActivityBeanById(item.getActivityId());
			
			//校验该活动是否数据当前用户
			if(!seller.getNick().equals(activity.getNick()))
			{
				request.setAttribute("error", "非法的请求");
				return "error";
			}
			
			//获取该活动下 本月 该商品的成交信息 人数、价格
			//数据格式为，deal_count, deal_price
			List<AnalysisDealByItem> dataList = this.activityRecordService.findDealCountByItem(item.getItemId(), new Date().getMonth() + 1);
			
			//size
			int size = dataList.size();
			
			//生成相应格式数据
			//数据名称
			String title = "";
			if(size > 0)
			{
				title = dataList.get(0).getItemName();
			}
			
			//x分段名称
			String[] xNameArr = new String[size];
			
			//x分段数据
			int[] inCountArr = new int[size];
			
			for(int i = 0; i < size; i++)
			{
				xNameArr[i] = "¥ " + dataList.get(i).getDealPrice();
				inCountArr[i] = dataList.get(i).getInCount();
			}
			
			request.setAttribute("title", title);
			request.setAttribute("xNameArr", JSONTranslator.toJSON(xNameArr, "utf-8", "utf-8"));
			request.setAttribute("inCountArr", JSONTranslator.toJSON(inCountArr, "utf-8", "utf-8"));
			return "analysis/ana_item";
		}
		catch (BaseException e)
		{
			request.setAttribute("error", "请求数据异常");
			return "error";
		}
	}

}
